//
//  PlayerViewController.m
//  mp3播放器
//
//  Created by Justsoso on 16/4/7.
//  Copyright © 2016年 Justsoso. All rights reserved.
//

#import "PlayerViewController.h"

#import <AVFoundation/AVFoundation.h>

#import "Mp3Model.h"
#import "PlayerLrc.h"

@interface PlayerViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSTimer *time;
    PlayerLrc *lrc;
    NSInteger currentRow;
}

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *singerLabel;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UITableView *lrcTabelView;


@property (nonatomic,strong) AVAudioPlayer *player;
@property (nonatomic,assign) BOOL playing;
@property (nonatomic,strong) Mp3Model *m;

@end

@implementation PlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    lrc  = [[PlayerLrc alloc] init];
    time = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateInfo) userInfo:nil repeats:YES];
    
    [self playChanged];
    
//    /* 隐藏分割线 */
//    self.lrcTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self.lrcTabelView reloadData];
    
    /* 后台播放音频设置 */
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    /* 让app支持接受远程控制事件 */
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
}


/* 返回按钮 */
- (IBAction)backBtnPressed:(id)sender
{
    /* 停止播放 */
    [self.player stop];
    /* 取消定时器 */
    [time invalidate];
    /* 释放内存 */
    time = nil;
    /* 返回列表页 */
    [self dismissViewControllerAnimated:YES completion:nil];
}

/* 播放按钮 */
- (IBAction)playBtnPressed:(UIButton *)sender
{
    self.playing = !self.playing;
    if (self.playing)
    {
        [sender setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        /* 停止暂停 */
        [self.player pause];
        /* 关闭定时器 */
        [time setFireDate:[NSDate distantFuture]];
    }
    else
    {
        [sender setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        /* 播放 */
        [self.player play];
        /* 开启定时器 */
        [time setFireDate:[NSDate distantPast]];
    }
}

/* 下一首 */
- (IBAction)nextBtnPressed:(id)sender
{
    /* 播放下一首 */
    [self nextPlayMusic];
}

/* 播放下一首 */
- (void)nextPlayMusic
{
    if (self.curSel == self.list.count-1)
    {
        self.curSel = -1;
    }
    self.curSel++;
    /* 改变播放页中的显示 */
    [self playChanged];
}

/* 播放上一首 */
- (IBAction)upBtnPressed:(id)sender
{
    if (self.curSel <= 0)
    {
        self.curSel = (int)self.list.count;
    }
    self.curSel--;
    /* 改变播放页中的显示 */
    [self playChanged];
}

/* 改变滑动条 */
- (IBAction)sliderChanged:(UISlider *)sender
{
    self.player.currentTime = self.slider.value;
}
- (IBAction)StopPlaySlider:(id)sender
{
    [self.player pause];
}
- (IBAction)replaySlider:(id)sender
{
    [self.player play];
}

/* 播放音乐 */
- (void)playMusic
{
    lrc.lrc = self.m.lrcname;
    [lrc parselrc];
    
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:self.m.filename withExtension:nil];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    
    self.slider.minimumValue = 0;
    self.slider.maximumValue = self.player.duration;
    /* 总时长 */
    self.totalTimeLabel.text = [NSString stringWithFormat:@"%02i:%02i",(int)self.player.duration / 60,(int)self.player.duration % 60];

    [self.player play];
}

- (void)updateInfo
{
    self.slider.value = self.player.currentTime;
    if (self.slider.value == 0)
    {
        /* 放完上一首自动播放下一首 */
        [self nextPlayMusic];
    }
    CGFloat currTime = self.player.currentTime;
    /* 播放时长 */
    self.currentTimeLabel.text = [NSString stringWithFormat:@"%02i:%02i",(int)currTime / 60,(int)currTime % 60];
    
    for (int i=0; i<lrc.timeArr.count; i++)
    {
        if (self.player.currentTime > [lrc.timeArr[i] floatValue])
        {
            currentRow = i;
        }
        else
        {
            break;
        }
    }
    // 使被选中的行移到中间
    [self.lrcTabelView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:currentRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    [self.lrcTabelView reloadData];
}

/* 得到改变的播放页的属性并更改 */
- (void)playChanged
{
    self.m = self.list[self.curSel];
    
    self.imageView.image = [UIImage imageNamed:self.m.icon];
    //    self.playing = YES;
    self.nameLabel.text = self.m.name;
    self.singerLabel.text = self.m.singer;
    [self playMusic];
}

#pragma mark - 歌词列表
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return lrc.wordArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    if (indexPath.row == currentRow)
    {
        cell.textLabel.textColor = [UIColor yellowColor];
    }
    else
    {
        cell.textLabel.textColor = [UIColor whiteColor];
    }
    
    cell.textLabel.text = lrc.wordArr[indexPath.row];
    
    return cell;
}
@end
